import React from 'react'
import {Card, Button, Form, Input, Select, Tree, Transfer, Modal, Table ,message} from 'antd'
import axios from 'axios'
import ETable from '../../components/ETable/index'
import menuConfig from '../../config/menuConfig'
import Utils from '../../utils/utils'
const FormItem = Form.Item;
const Option = Select.Option;
const TreeNode = Tree.TreeNode;
export default class Order extends React.Component{

    state={
        isRoleVisible:false,
        isPermVisible:false,
        isPermVisible:false
    }

    componentWillMount(){
       axios.get("https://www.studyinghome.com/mock/5e4ca5d80167590746b7615d/example/perss")
      
        .then((res) => {
             this.setState({
                userName:res.data.list
             })
        })
     
    }
    onRowClick = (record,index) => {
        let selectKey=[index];
        this.setState({
            selectedRowKeys:selectKey,
            selectedItem: record
        })
    }
    // 角色创建
    handleRole = ()=>{
        this.setState({
            isRoleVisible:true
        })
    }

    // 角色提交
    handleRoleSubmit = ()=>{
        
        this.roleForm.props.form.resetFields();
        console.log(this.roleForm.props.form)
        message.success("创建成功")
        this.setState({
            isRoleVisible:false
        })
      
    }

    handlePermission = ()=>{
        let item = this.state.selectedItem
        if(!item) {
            Modal.info({
                title:"提示",
                content:"请选择用户"
            })
            return 
        }
        this.setState({
            isPermVisible:true,
            detailInfo: item
        })
    }

    handlePermEditSubmit = ()=>{
       
    }

    // 用户授权
    handleUserAuth = ()=>{
        if (!this.state.selectedItem) {
            Modal.info({
                title: '信息',
                content: '未选中任何项目'
            })
            return;
        }
        this.getRoleUserList(this.state.selectedItem.id);
        this.setState({
            isUserVisible: true,
            isAuthClosed: false,
            detailInfo: this.state.selectedItem
        });
    }
    getRoleUserList = (id)=>{
        axios.get("https://www.studyinghome.com/mock/5e4ca5d80167590746b7615d/example/user_list")
        .then((res) => {
           if(res) {
            this.getAuthUserList(res.data.list);
           }
        })
    }
    // 筛选目标用户
    getAuthUserList = (dataSource) => {
        const mockData = [];
        const targetKeys = [];
        if (dataSource && dataSource.length > 0) {
            for (let i = 0; i < dataSource.length; i++) {
                const data = {
                    key: dataSource[i].user_id,
                    title: dataSource[i].user_name,
                    status: dataSource[i].status,
                };
                if (data.status == 1) {
                    targetKeys.push(data.key);
                }
                 mockData.push(data);
            }
        }
        this.setState({
            mockData, 
            targetKeys
        });
    };
    
    patchUserInfo = (targetKeys) => {
        this.setState({
            targetKeys: targetKeys
        });
    };

    // 用户授权提交
    handleUserSubmit = ()=>{
        this.setState({
            isUserVisible:false
        })
    }
    render(){
        const columns = [
            {
                title: '角色ID',
                dataIndex: 'id'
            }, {
                title: '角色名称',
                dataIndex: 'role_nam',
            },{
                title: '创建时间',
                dataIndex: 'create_time',
                render: Utils.formatTime
            }, {
                title: '使用状态',
                dataIndex: 'status',
                render(status){
                    if (status == 1) {
                        return "启用"
                    } else {
                        return "停用"
                    }
                }
            }, {
                title: '授权时间',
                dataIndex: 'authorize_time',
                 render: Utils.formatTime
            }, {
                title: '授权人',
                dataIndex: 'authorize_user_name',
            }
        ];
        const selectedRowKeys = this.state.selectedRowKeys
        const rowSelection = {
            type:"radio",
            selectedRowKeys
        
        }
        return (
            <div>
                <Card className="card-wrap">
                    <Button type="primary" onClick={this.handleRole}>创建角色</Button>
                    <Button type="primary" onClick={this.handlePermission}>设置权限</Button>
                    <Button type="primary" onClick={this.handleUserAuth}>用户授权</Button>
                </Card>  
                <Modal 
                    title="创建角色"
                    visible={this.state.isRoleVisible}
                    onOk={this.handleRoleSubmit}
                    onCancel={()=> {
                        this.roleForm.props.form.resetFields();
                        this.setState({
                            isRoleVisible:false
                        })
                    }}
                >
                     <RoleForm wrappedComponentRef={(inst) => this.roleForm = inst }/>
                </Modal> 
                <Modal
                       title="权限设置"
                       visible={this.state.isPermVisible}
                       width={600}
                       onOk={this.handlePermEditSubmit}
                       onCancel={()=>{
                           this.setState({
                               isPermVisible:false
                           })
                       }}>
                           <PermEditForm
                                 wrappedComponentRef={(inst) => this.roleForm = inst }
                                 detailInfo={this.state.detailInfo}
                                 patchMenuInfo={(checkedKeys)=>{
                                    this.setState({
                                        menuInfo: checkedKeys
                                    });
                                }}
                           />
                </Modal>    
                <Modal
                       title="用户授权"
                       visible={this.state.isUserVisible}
                       width={800}
                       onOk={this.handleUserSubmit}
                       onCancel={()=>{
                           this.setState({
                               isUserVisible:false
                           })
                       }}>
                           <RoleAuthForm 
                                  wrappedComponentRef={(inst) => this.userAuthForm = inst }
                                  isClosed={this.state.isAuthClosed}
                                  detailInfo={this.state.detailInfo}
                                  targetKeys={this.state.targetKeys}
                                  mockData={this.state.mockData}
                                  patchUserInfo={this.patchUserInfo}
                           />
                </Modal>    
                <Table
                    columns={columns}
                    dataSource={this.state.userName}
                    selectedRowKeys={this.state.selectedRowKeys}
                    rowSelection={rowSelection}
                    onRow={(record, index) => {
                        return{
                            onClick:()=> {
                                this.onRowClick(record,index);
                            }
                        }
                    }}
                >
                   
                </Table>
            </div>
        );
    }
}

// 角色创建
class RoleForm extends React.Component{
   
    render() {
        const { getFieldDecorator} = this.props.form
        const fromList = {
            labelCol:{span: 5},
            wrapperCol:{span: 13}
        }
        return(
           <Form>
               <FormItem label="角色" {...fromList}>
                   {
                       getFieldDecorator("role_name",{

                       })(
                        <Input type="text" placeholder="请输入角色名称"/>
                       )
                   }
               </FormItem>
               <FormItem label="状态" {...fromList}>
                   {
                       getFieldDecorator("state",{
                       })(
                            <Select>
                                <Option value={0}>开启</Option>
                                <Option value={1}>关闭</Option>
                            </Select>
                       )
                   }
               </FormItem>
           </Form>
        )
    }
}
RoleForm = Form.create({})(RoleForm)


//权限设置
class PermEditForm extends React.Component{
    onCheck = () => {

    }
    onCheck = (checkedKeys) => {
        this.props.patchMenuInfo(checkedKeys);
    };
    renderTreeNodes = (data)=> {
        console.log(data, '')
       return   data.map((item) => {
            if(item.children) {
                return <TreeNode title={item.title} key={item.key}>
                            {this.renderTreeNodes(item.children)}
                       </TreeNode>
            } else {
               return  <TreeNode title={item.title} key={item.key}>
                          
                         </TreeNode>
            }
        })
    }
    render() {
        let detail_info = this.props.detailInfo
        const { getFieldDecorator} = this.props.form;
        const formItemLayout = {
            labelCol: {span: 5},
            wrapperCol: {span: 18}
        };
        return(
            <Form layout="horizontal">
                <FormItem label="角色名称" {...formItemLayout}>
                   <Input disabled maxLength="8" placeholder={detail_info.role_nam}/>
                </FormItem>
                <FormItem label="状态" {...formItemLayout}> 
                    {
                        getFieldDecorator("status",{
                            initialValue:1
                        })(
                            <Select
                                style={{ width: 80}}
                                placeholder="启用"
                            >
                                <Option value={1}>启用</Option>
                                <Option value={0}>未启用</Option>
                            </Select>
                        )
                    }
                </FormItem>
                <Tree
                    checkable
                    defaultExpandAll
                    onCheck={(checkedKeys) => {
                        this.onCheck(checkedKeys)
                    }}
                    checkedKeys={true}
                >
                    <TreeNode title="平台权限" key="platform_all">
                        {this.renderTreeNodes(menuConfig)}
                    </TreeNode>
                </Tree>
            </Form>
        )
    }
}
PermEditForm = Form.create({})(PermEditForm)
// 用户授权
class RoleAuthForm extends React.Component {

    // filterOption = (inputValue, option) => {
    //     return option.title.indexOf(inputValue) > -1;
    // };
    // handleChange = (targetKeys) => {
    //     this.props.patchUserInfo(targetKeys);
    // };

    render() {
        const formItemLayout = {
            labelCol: {span: 5},
            wrapperCol: {span: 18}
        };
        const detail_info = this.props.detailInfo;
        return (
            <Form layout="horizontal">
                <FormItem label="角色名称：" {...formItemLayout}>
                    <Input disabled maxLength={8} placeholder={detail_info.role_nam}/>
                </FormItem>
                <FormItem label="选择用户：" {...formItemLayout}>
                    <Transfer
                        listStyle={{width: 200,height: 400}}
                        dataSource={this.props.mockData}
                        showSearch
                        titles={['待选用户', '已选用户']}
                        searchPlaceholder='输入用户名'
                        filterOption={this.filterOption}
                        targetKeys={this.props.targetKeys}
                        onChange={this.handleChange}
                        render={item => item.title}
                    />
                </FormItem>
            </Form>
        )
    }
}
RoleAuthForm = Form.create({})(RoleAuthForm);